<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Image;
use think\Db;
class Service extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("name")) {
            $map['s.name'] = ["like", "%" . $this->request->param("name") . "%"];
        }
        // if($this->request->param('type')){
        //         $map['type']=$this->request->param('type');
        // }else{
        //         $map['type']=0;
        // }
    }
    public function index(){
            // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }

    	$model = $this->getModel();
    	// 列表过滤器，生成查询Map对象
    	// $map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete]);

    	// 特殊过滤器，后缀是方法名的
    	$actionFilter = 'filter' . $this->request->action();
    	if (method_exists($this, $actionFilter)) {
    	    $this->$actionFilter($map);
    	}

    	

        $map['s.isdelete']=0;
    	$limit=12;
        $list=Db::table('tp_service')->alias('s')
                               ->join('img i','s.id=i.relation_id and i.isdelete=0 and i.folder=\'service\'','LEFT')
                               ->field('s.*,i.url')
                               ->where($map)
                               ->order('create_time desc')
                               ->paginate($limit);
        $list2=$list->toArray();
        foreach ($list2['data'] as &$val) {
            $val['img']=imghandle($val['url'],'sm_');
        }
    	
    	$p=input('get.p')?:1;
        $offset=($p-1)*$limit+1;
    	$this->view->assign(['list'=>$list2['data'],'page'=>$list->render(),'offset'=>$offset,'count'=>$list->total()]);
    	// $this->datalist($model, $map);
        return $this->view->fetch();
    }
    /**
    * 服务分类列表显示
    * Service/service_class 
    * 2018.01.15
    * BY HF
    */
    public function service_class(){
        $map=['s.isdelete'=>0];
        $limit=12;
        $list=Db::name('service_class')->alias('s')
                                       ->join('img i','s.id=i.relation_id and i.isdelete=0 and i.folder=\'service_class\'','LEFT')
                                       ->field('s.*,i.url')
                                       ->where($map)->order('create_time desc')->paginate($limit);
        $list2=$list->toArray();
        foreach ($list2['data'] as &$val) {
            $val['img']=imghandle($val['url'],'sm_');
        }
        $p=input('get.p')?:1;
        $offset=($p-1)*$limit+1;
        $this->view->assign(['list'=>$list2['data'],'page'=>$list->render(),'offset'=>$offset,'count'=>$list->total()]);
        return $this->view->fetch('class');
    }

    /**
    * 服务分类编辑
    * Service/class_edit
    * 2018.01.15
    * BY HF
    */
    public function class_edit(){
        $controller = $this->request->controller();
        if($this->request->isAjax()){
            $param=$this->request->post(); 
            $param['update_time']=date('Y-m-d H:i:s');
            if(!isset($param['img_id'])){
                Db::name('service_class')->update($param);
                return ajax_return_adv("编辑成功");
            }
            $imgid=$param['img_id'];
            unset($param['img_id']);
            Db::startTrans();
            try {
                // 提交事务
                Db::name('service_class')->update($param);
                Db::name('img')->update(['id'=>$imgid,'relation_id'=>$param['id']]);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }
            return ajax_return_adv("编辑成功");
        }else{
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel($controller)->find($id);
            $vo=Db::table('tp_service_class')->alias('s')
                                   ->join('img i','s.id=i.relation_id and i.folder=\'service_class\' and s.isdelete=0 and i.isdelete=0','LEFT')
                                   ->field('s.*,i.url,i.id imgid')
                                   ->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }
            $vo['img']=imghandle($vo['url'],'sm_');
            $vo['mdimg']=imghandle($vo['url'],'md_');
            $this->view->assign("vo", $vo);
            return $this->view->fetch('editClass');    
        }
    }

    /**
    * 服务分类搭配服务
    * Service/assort
    * @param id
    * 2018.01.16
    * BY HF
    */
    public function assort(){
        if($this->request->isAjax()){
            $param=$this->request->param();
            $ids=json_encode($param['ids']);                    
            $id=$param['id'];
            $price=0;
            foreach ($param['ids'] as $val) {
                $p=Db::name('service')->where('id',$val)->value('price');
                $price+=$p;
                # code...
            }
            if(Db::name('service_class')->update(['id'=>$id,'price'=>$price,'ids'=>$ids,'update_time'=>date('Y-m-d H:i:s')])){
                 return ajax_return_adv("编辑成功");
            }else{
                 return ajax_return_adv_error("编辑失败，稍后再试");
            }
        }else{
            $id=$this->request->param('id');
            $sclist=Db::name('service_class')->find($id);
            $ids=json_decode($sclist['ids']?:'[]');
            $map=['s.isdelete'=>0];
            $list=Db::table('tp_service')->alias('s')
                                   ->join('img i','s.id=i.relation_id and i.isdelete=0 and i.folder=\'service\'','LEFT')
                                   ->field('s.*,i.url')
                                   ->where($map)
                                   ->order('create_time desc')
                                   ->select();
           
            foreach ($list as &$val) {
                if(in_array($val['id'], $ids)){
                    $val['selected']=1;
                }else{
                    $val['selected']=0;
                }
                $val['img']=imghandle($val['url'],'sm_');
            }
            $this->view->assign(['list'=>$list,'id'=>$id]);
            return $this->view->fetch();
        }
    }



    /**
    * 服务分类删除
    * Service/delete_class
    * @param id  
    * 2018.01.15
    * BY HF
    */
    public function delete_class(){
        $id=$this->request->param('id');
        if(Db::name('service_class')->update(['id'=>$id,'isdelete'=>1,'update_time'=>date('Y-m-d H:i:s')])){
             return ajax_return_adv('删除成功');   
        }
        return ajax_return_adv_error('删除失败');
    }

    /**
    *图片上传方法
    *Service/upload
    *2017.12.18
    *BY HF
    */
    public function upload(){
    	$file=$this->request->file('Filedata');
    	$path=ROOT_PATH . 'public' . DS . 'uploads' . DS .$this->request->param('folder');
    	if($file){
	        $info = $file->move($path);
	        if($info){
	            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
	            // echo $info->getSaveName();
	            // 输出 42a79759f284b767dfcb2a0197904287.jpg
	            // echo $info->getFilename(); 
	            $image = Image::open($path.'/'.$info->getSaveName());
	            // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
	            $image->thumb(400,400)->save($path . DS . date('Ymd') . DS .'md_'.$info->getFilename());
	            $image->thumb(100,100,Image::THUMB_CENTER)->save($path . DS . date('Ymd') . DS .'sm_'.$info->getFilename());

	            $data=[
	            	'relation_id'=>0,
	            	'url'=>$info->getSaveName(),
	            	'folder'=>$this->request->param('folder'),
	            	'create_time'=>date('Y-m-d H:i:s'),
	            	'last_time'=>date('Y-m-d H:i:s'),
	            ];
	            $id=Db::name('img')->insertGetId($data);
	            $html="
	            <div class='appendimg' id='appendimg'>
                     <img src='/uploads/".$this->request->param('folder').'/'.date('Ymd').'/sm_'.$info->getFilename()."'>  
                 </div>
                 <div class='del' data-index='{$id}' data-imgpath='/uploads/".$this->request->param('folder').'/'.$info->getSaveName()."'>
                     <i class='Hui-iconfont'>&#xe609;</i>
                 </div>
                 <input type='hidden' name='img_id' value='{$id}'>
	            ";
	            return $html;
	        }else{
	            // 上传失败获取错误信息
	            return $file->getError();
	        }
	    }
    }
    /**
    *Service/del_upload_img
    *@param 图片id 必须
    *删除上传图片方法
    *2017.12.18
    *BY HF
    */
    public function del_upload_img(){
    	$id=$this->request->param('id');
    	if(Db::name('img')->update(['id'=>$id,'isdelete'=>1])){
    		return 1;
    	}else{
    		return 0;
        }
    }
    /**
    *编辑方法
    *Service/edit
    *2017.12.18
    *BY HF
    */
    public function edit(){
    	$controller = $this->request->controller();
    	if($this->request->isAjax()){
			$param=$this->request->post(); 
			$param['update_time']=date('Y-m-d H:i:s');
			if(!isset($param['img_id'])){
				Db::name('service')->update($param);
				return ajax_return_adv("编辑成功");
			}
			$imgid=$param['img_id'];
			unset($param['img_id']);
			Db::startTrans();
			try {
			    // 提交事务
				Db::name('service')->update($param);
				Db::name('img')->update(['id'=>$imgid,'relation_id'=>$param['id']]);
			    Db::commit();
			} catch (\Exception $e) {
			    // 回滚事务
			    Db::rollback();
			    return ajax_return_adv_error($e->getMessage());
			}
			return ajax_return_adv("编辑成功");
    	}else{
    		$id = $this->request->param('id');
    		if (!$id) {
    		    throw new HttpException(404, "缺少参数ID");
    		}
    		$vo = $this->getModel($controller)->find($id);
    		$vo=Db::table('tp_service')->alias('s')
    							   ->join('img i','s.id=i.relation_id and i.folder=\'service\' and s.isdelete=0 and i.isdelete=0','LEFT')
    							   ->field('s.*,i.url,i.id imgid')
    							   ->find($id);
    		if (!$vo) {
    		    throw new HttpException(404, '该记录不存在');
    		}
    		$vo['img']=imghandle($vo['url'],'sm_');
    		$vo['mdimg']=imghandle($vo['url'],'md_');
    		$this->view->assign("vo", $vo);
            return $this->view->fetch('edit');    
    	}
    }
    /**
    *添加方法
    *Service/add
    *
    *2017.12.18
    *BY HF
    */
    public function add(){
    	$controller = $this->request->controller();
    	if($this->request->isAjax()){
    		// $param=$this->request->post(); 
    		$param = $this->request->except(['id','type']);
    		$param['create_time']=date('Y-m-d H:i:s');
    		$param['update_time']=date('Y-m-d H:i:s');
    		if(!isset($param['img_id'])){
	    		Db::name('service')->insertGetId($param);
    			return ajax_return_adv("添加成功");
    		}
    		$img_id=$param['img_id']; //图片表中的ID
    		unset($param['img_id']);
    		Db::startTrans();
    		try {
    		    // 提交事务
    			$relation_id=Db::name('service')->insertGetId($param);
    			Db::name('img')->update(['id'=>$img_id,'relation_id'=>$relation_id]);
    		    Db::commit();
    		} catch (\Exception $e) {
    		    // 回滚事务
    		    Db::rollback();
    		    return ajax_return_adv_error($e->getMessage());
    		}
	    	return ajax_return_adv("添加成功");
    	}else{
            $type=$this->request->param('type')?:0;
            if($type){
                return $this->view->fetch('edit');
            }
            return $this->view->fetch('editClass');
    	}
    }
    /**
    * 添加服务分类
    * Service/addClass
    * 2018.01.15
    * BY HF 
    */
    public function addClass(){
        if($this->request->isAjax()){

            $param = $this->request->except(['id']);
            $param['create_time']=date('Y-m-d H:i:s');
            $param['update_time']=date('Y-m-d H:i:s');
            if(!isset($param['img_id'])){
                Db::name('service_class')->insertGetId($param);
                return ajax_return_adv("添加成功");
            }

            $img_id=$param['img_id']; //图片表中的ID
            unset($param['img_id']);
            Db::startTrans();
            try {
                // 提交事务
                $relation_id=Db::name('service_class')->insertGetId($param);
                Db::name('img')->update(['id'=>$img_id,'relation_id'=>$relation_id]);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }
            return ajax_return_adv("添加成功");
        }
        return $this->view->fetch('editClass');
    }
    /**
    *删除方法
    *Service/delete
    *2018.01.15
    *BY HF
    */
    public function delete(){
        $id=$this->request->param('id');
        $count=Db::name('service')->where(['pid'=>$id,'isdelete'=>0])->count();

        if($count){
            return ajax_return_adv_error('该分类下有子分类，移除子分类才能删除该分类');
        }
        if(Db::name('service')->update(['id'=>$id,'isdelete'=>1,'update_time'=>date('Y-m-d H:i:s')])){
            return ajax_return_adv_error('删除成功');
        }else{
            return ajax_return_adv('删除失败,请稍后再试', '');
        }
    }
}
